package dameng

import (
	"database/sql"
	"fmt"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
)

// Open creates and returns an underlying sql.DB object for dameng.
func (d *Driver) Open(config *gdb.ConfigNode) (db *sql.DB, err error) {
	var (
		source               string
		underlyingDriverName = "dm"
	)
	// Data Source Name of DM8:
	// dm://userName:password@ip:port/dbname?schema=schemaName
	// dm://userName:password@DW/dbname?DW=(192.168.1.1:5236,192.168.1.2:5236)
	if config.Link != "" {
		config = parseConfigNodeLink(config)
	}
	source = fmt.Sprintf(
		"dm://%s:%s@%s:%s",
		config.User, config.Pass, config.Host, config.Port,
	)
	if config.Name != "" {
		source = fmt.Sprintf(`%s/%s`, source, config.Name)
	}
	if config.Extra != "" {
		source = fmt.Sprintf("%s?%s", source, config.Extra)
	}
	if db, err = sql.Open(underlyingDriverName, source); err != nil {
		err = gerror.WrapCodef(
			gcode.CodeDbOperationError, err,
			`Dameng.Open failed for driver "%s" by source "%s"`, underlyingDriverName, source,
		)
		return nil, err
	}
	return
}
